import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';
import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Descriptions,
  Button,
  Table,
  Divider,
  Modal,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import { TableListItem } from './data';

import SavePartition from './components/SavePartition';

interface PartitionListProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  location: { query: any };
}

interface PartitionListState {
  searchValues: any;
  saveVisible: boolean;
  values: any;
  delVisible: boolean;
  delId: number;
  rowId: number;
}

@connect(({ partitionList: { dataInfo } }: any) => ({ dataInfo }))

class PartitionListElem extends Component<PartitionListProps, PartitionListState> {
  columns = [
    { title: '分区号', dataIndex: 'region', width: '18%' },
    { title: '层号', dataIndex: 'layer', width: '18%' },
    { title: '描述', dataIndex: 'desc', width: '18%' },
    {
      title: '包裹编号范围',
      dataIndex: 'startPkgnum',
      width: '18%',
      render: (text: string, row: TableListItem) => (text ? `${text}~${row.endPkgnum}` : '--'),
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (text: number, row: TableListItem) => {
        const { location: { query } } = this.props;
        return (
          <Fragment>
            <div>
              {query && query.type === '货架' && (
                <span>
                  <span className="operLink" onClick={() => this.handleChangeSave(true, row)}>
                    配置编号
                  </span>
                  <Divider type="vertical" />
                </span>
              )}
              <span
                className="operLink"
                onClick={() => this.handleHistoryOrder(row)}
              >
                查看历史订单
              </span>
              <Divider type="vertical" />
              <span className="operLink" onClick={() => this.handleChangeDel(true, text)}>
                删除
              </span>
            </div>
          </Fragment>
        );
      },
    },
  ];

  state: PartitionListState = {
    searchValues: {
      shelfId: 0,
      pageIndex: 1,
      pageSize: 20,
    },
    saveVisible: false,
    values: {},
    delVisible: false,
    delId: 0,
    rowId: 0,
  };

  componentDidMount() {
    const { location: { query } } = this.props;
    if (query && query.id) {
      const { searchValues } = this.state;
      const params = { ...searchValues, shelfId: query.id };
      this.setState({ searchValues: params }, () => this.fetchDataInfo());
    }
  }

  componentDidUpdate(props: any) {
    const { location: { query } } = this.props;
    if (Object.keys(query).length > 0
      && !_.isEqual(query, props.location.query)
    ) {
      this.fetchDataInfo();
    }
  }

  fetchDataInfo = () => {
    const { searchValues } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'partitionList/fetch',
      payload: searchValues,
    });
  };

  handleHistoryOrder = (record: any) => {
    const { location: { query } } = this.props;
    const params = {
      name: query.name,
      code: query.code,
      layer: record.layer,
      desc: record.desc,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '查看历史订单',
      url: `/basic/shelvesToHeap/list/partition/order?${qs.stringify(params)}`,
    });
  }

  handleChangeSave = (saveVisible: boolean, values: any = {}) => {
    this.setState({ saveVisible, values });
  };

  handleChangeDel = (delVisible: boolean, id?: any) => {
    this.setState({ delVisible, delId: id || 0 });
  };

  handleDelSubmit = () => {
    const { searchValues: search, delId: id } = this.state;
    const params = { search, id };
    this.fetchAction('delete', params);
    this.handleChangeDel(false);
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    this.setState({ searchValues: params }, () => this.fetchAction('fetch', params));
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { location: { query } } = this.props;
    if (typeName === 'saveOrUpdate' && query) {
      const params = { shelfId: query.id, pageIndex: 1, pageSize: 20 };
      this.setState({
        searchValues: params,
      });
      payload = { ...payload, search: params };
      this.handleChangeSave(false);
    }

    const type = typeName.indexOf('common') >= 0
      ? typeName : `partitionList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      saveVisible,
      values,
      searchValues: { pageIndex, pageSize },
      delVisible,
    } = this.state;

    const {
      dataInfo,
      location: { query },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} title="设置分区">
          <Descriptions bordered size="small" column={2}>
            <Descriptions.Item label="物流中心">{query.gardenName}</Descriptions.Item>
            <Descriptions.Item label={query.type}>{query.name}</Descriptions.Item>
          </Descriptions>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={() => this.handleChangeSave(true)}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <SavePartition
          saveVisible={saveVisible}
          values={values}
          shelvesId={query ? query.id : 0}
          fetchAction={this.fetchAction.bind(this)}
          changeSave={this.handleChangeSave.bind(this)}
        />

        <Modal
          visible={delVisible}
          onOk={this.handleDelSubmit}
          onCancel={() => this.handleChangeDel(false)}
        >
          <p>确定要删除当前分区吗？</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<PartitionListProps>()(PartitionListElem);
